package com.powerunion.datacollection.persistence.db.jdbc.base;

import java.sql.*;
import java.util.*;

import org.apache.log4j.Logger;
import com.powerunion.util.log.LogHelper;

/**
 * 结果集处理实现类
 * @author qyw
 *
 */
final public class ResultSetHandler {
  private int rowCount;
  private int columnCount;
  private int[] columnTypes;
  private String[] columnNames;
  private List sqlResultSet; //数据结果集
  private boolean isBuilded = false;
  private static Logger logger = LogHelper.getInstance().getLogger(ResultSetHandler.class);
  public ResultSetHandler() {
    sqlResultSet = new ArrayList();
  }

  public ResultSetHandler(int dataSize) {
    sqlResultSet = new ArrayList(dataSize);
  }

  public void handle(ResultSet rs) throws SQLException {
    isBuilded = true;
    if (rowCount == 0) {
      ResultSetMetaData rsmd = rs.getMetaData();
      columnCount = rsmd.getColumnCount();
      columnTypes = new int[columnCount];
      columnNames = new String[columnCount];
      for (int i = 0; i < columnCount; i++) {
        columnTypes[i] = rsmd.getColumnType(i + 1);
        //columnNames[i] = rsmd.getColumnName(i + 1);
        columnNames[i] = rsmd.getColumnLabel(i + 1);
      }
    }
    rowCount++;
    processRow(rs);
  }

  private void processRow(ResultSet rs) throws SQLException {
    //HashMap rowMap = new HashMap(columnCount);
    Map rowMap = new LinkedHashMap(columnCount); //保持顺序
    try {
      for (int i = 0; i < columnCount; i++) {
        //String key = columnNames[i].trim().toUpperCase();
        String key = columnNames[i].trim().toLowerCase();
        Object value = rs.getObject(i + 1); //(columnNames[i]);?
        rowMap.put(key, value);
      }
      sqlResultSet.add(rowMap);
    }
    catch (SQLException sqe) {
      logger.error("取回记录出错", sqe);
      throw sqe;
    }
  }

  public int getColumnCount() {
    return columnCount;
  }

  public String[] getColumnNames() {
    if (this.isBuilded) {
      return columnNames;
    }
    else {
      throw new RuntimeException("execute the access()method,first!");
    }
  }

  public int[] getColumnTypes() {
    if (this.isBuilded) {
      return columnTypes;
    }
    else {
      throw new RuntimeException("execute the access()method,first!");
    }
  }

  public int getRowCount() {
    return rowCount;
  }

  public final List getResultDataSet() throws
      DBAccessException {
    if (!isBuilded) {
      if (logger.isDebugEnabled()) {
        logger.debug("数据集没有初始化！");
        logger.debug("可能没有数据集返回");
      }
      //throw new DBAccessException("数据集没有初始化！");
    }
    return sqlResultSet;
  }

  
}
